#include "Image.h"
#include "ResourceManager.h"

namespace glow
{
	using namespace std;
	
	Image::Image() : _texture(NULL)
	{
		_pos.x = 0;
		_pos.y = 0;
	}

	Image::Image(string filename) : _texture(NULL)
	{
		load(filename);
	}

	Image::~Image()
	{
		if(_texture)
			_texture->release();
	}

	void Image::load(string filename)
	{
		if(_texture)
		{
			_texture->release();
			_texture = NULL;
		}
		
		ResourceManager *rs = ResourceManager::getInstance();
		_texture = rs->get<Texture>(filename);
		
		if(!_texture)
			_texture = new Texture(filename);
		
		if(_texture)
		{
			_pos.x = 0;
			_pos.y = 0;
			
			_size = _texture->getSize();
		}
	}
	
	void Image::draw() const
	{	
		glColor3ub(255,255,255);
		glDisable(GL_LIGHTING);
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, _texture->getGLID());
		glBegin(GL_QUADS);
		glTexCoord2f(1.f,0.f); glVertex2d(_pos.x+_size.x, _pos.y);
		glTexCoord2f(1.f,1.f); glVertex2d(_pos.x+_size.x, _pos.y+_size.y);
		glTexCoord2f(0.f,1.f); glVertex2d(_pos.x, _pos.y+_size.y);
		glTexCoord2f(0.f,0.f); glVertex2d(_pos.x, _pos.y);		
		glEnd();
		glBindTexture(GL_TEXTURE_2D, 0);
		glDisable(GL_TEXTURE_2D);
		glEnable(GL_LIGHTING);
	}
	
	void Image::setSize(Vector2i size)
	{
		_size = size;
	}
	
    const Vector2i &Image::getSize() const
    {
		return _size;
	}
        
    void Image::setPosition(Vector2i position)
    {
		_pos = position;
	}
	
    const Vector2i &Image::getPosition() const
    {
		return _pos;
	}
}
